import { Vec3 } from '@/core/types';
import { Entity } from '@/entities/Entity';
import { aiService, fallbackService } from './AIService';
import { 
  getEntityPersona, 
  getRandomGreeting, 
  shouldInitiateConversation,
  generateAutonomousMessage,
  generatePersonalityPrompt,
  adjustResponseByPersonality,
  isActiveTime,
  getBehaviorPatterns
} from './EntityPersonas';
import { ConversationContext, GameContext, ChatMessage } from './types';

// 自主对话状态接口
interface AutoChatState {
  entityId: string;
  lastChatTime: number;
  cooldownDuration: number;
  isInRange: boolean;
  hasGreeted: boolean;
}

// 自主对话管理器
export class AutoChatManager {
  private entityStates: Map<string, AutoChatState> = new Map();
  private detectionRange = 10; // 默认玩家接近检测范围（格）
  private cooldownDuration = 10 * 1000; // 临时降低到10秒用于测试
  private gameContextProvider?: (entity: Entity) => GameContext;
  private onAutoChatCallback?: (entity: Entity, message: string) => void;

  constructor() {
    console.log('AutoChatManager 初始化完成 - 支持个性化对话系统');
  }

  /**
   * 更新自主对话系统
   * @param playerPosition 玩家位置
   * @param entities 所有实体列表
   */
  public update(playerPosition: Vec3, entities: Entity[]): void {
    const currentTime = Date.now();
    
    console.log(`[AutoChat] 更新自主对话系统 - 玩家位置: (${playerPosition.x.toFixed(1)}, ${playerPosition.y.toFixed(1)}, ${playerPosition.z.toFixed(1)}), 实体数量: ${entities.length}`);

    // 检查每个实体
    for (const entity of entities) {
      if (!this.canEntityAutoChat(entity)) {
        console.log(`[AutoChat] 实体 ${entity.getType()} (${entity.getId()}) 不支持自主对话`);
        continue;
      }

      const entityId = entity.getId();
      const entityPos = entity.getPosition();
      const distance = this.calculateDistance(playerPosition, entityPos);
      
      // 使用个性化的检测范围
      const personalizedRange = this.getPersonalizedDetectionRange(entity);
      const isInRange = distance <= personalizedRange;

      console.log(`[AutoChat] 实体 ${entity.getType()} (${entityId}) - 位置: (${entityPos.x.toFixed(1)}, ${entityPos.y.toFixed(1)}, ${entityPos.z.toFixed(1)}), 距离: ${distance.toFixed(1)}, 检测范围: ${personalizedRange}, 在范围内: ${isInRange}`);

      // 获取或创建实体状态
      let state = this.entityStates.get(entityId);
      if (!state) {
        state = {
          entityId,
          lastChatTime: 0,
          cooldownDuration: this.cooldownDuration,
          isInRange: false,
          hasGreeted: false
        };
        this.entityStates.set(entityId, state);
        console.log(`[AutoChat] 为实体 ${entityId} 创建新状态`);
      }

      // 检查玩家是否刚进入范围
      const justEnteredRange = isInRange && !state.isInRange;
      const wasInRange = state.isInRange;
      state.isInRange = isInRange;

      console.log(`[AutoChat] 实体 ${entityId} - 之前在范围内: ${wasInRange}, 现在在范围内: ${isInRange}, 刚进入范围: ${justEnteredRange}`);

      // 如果玩家刚进入范围，或者在范围内且满足触发条件，触发自主对话
      if ((justEnteredRange || isInRange) && this.canTriggerAutoChat(state, currentTime, entity)) {
        console.log(`[AutoChat] 触发实体 ${entityId} 的自主对话 (刚进入: ${justEnteredRange}, 在范围内: ${isInRange})`);
        this.triggerAutoChat(entity, state);
      } else if (justEnteredRange) {
        console.log(`[AutoChat] 实体 ${entityId} 刚进入范围但不满足触发条件`);
      } else if (isInRange) {
        console.log(`[AutoChat] 实体 ${entityId} 在范围内但不满足触发条件 (冷却中或个性化判断失败)`);
      }

      // 如果玩家离开范围，重置问候状态
      if (!isInRange && state.hasGreeted) {
        state.hasGreeted = false;
        console.log(`[AutoChat] 重置实体 ${entityId} 的问候状态`);
      }
    }

    // 清理不存在的实体状态
    this.cleanupEntityStates(entities);
  }

  /**
   * 检查实体是否可以进行自主对话
   */
  private canEntityAutoChat(entity: Entity): boolean {
    if (!entity || !entity.isAlive()) {
      return false;
    }

    const entityType = entity.getType();
    const persona = getEntityPersona(entityType);
    return persona !== null;
  }

  /**
   * 检查是否可以触发自主对话
   */
  private canTriggerAutoChat(state: AutoChatState, currentTime: number, entity: Entity): boolean {
    // 检查冷却时间
    const timeSinceLastChat = currentTime - state.lastChatTime;
    const cooldownPassed = timeSinceLastChat >= state.cooldownDuration;

    console.log(`[AutoChat] 🔍 检查触发条件 ${entity.getId()} - 已问候: ${state.hasGreeted}, 冷却时间已过: ${cooldownPassed} (${(timeSinceLastChat/1000).toFixed(1)}s / ${(state.cooldownDuration/1000).toFixed(1)}s)`);

    // 基础条件：还没有问候过或者冷却时间已过
    const basicCondition = !state.hasGreeted || cooldownPassed;
    if (!basicCondition) {
      console.log(`[AutoChat] ❌ 基础条件不满足 ${entity.getId()} - 需要等待冷却`);
      return false;
    }

    // 使用个性化判断是否应该发起对话
    const gameContext = this.getGameContext(entity);
    const personalityContext = {
      timeOfDay: gameContext.timeOfDay,
      weather: gameContext.weather,
      distance: this.detectionRange,
      timeSinceLastChat: timeSinceLastChat / (60 * 1000) // 转换为分钟
    };

    console.log(`[AutoChat] 🎭 个性化上下文:`, personalityContext);
    const shouldInitiate = shouldInitiateConversation(entity.getType(), personalityContext);
    console.log(`[AutoChat] ${shouldInitiate ? '✅' : '❌'} 个性化判断结果 ${entity.getId()}: ${shouldInitiate}`);

    return shouldInitiate;
  }

  /**
   * 触发自主对话
   */
  private async triggerAutoChat(entity: Entity, state: AutoChatState): Promise<void> {
    try {
      console.log(`[AutoChat] 🎯 触发自主对话: ${entity.getType()} (${entity.getId()})`);
      
      const currentTime = Date.now();
      state.lastChatTime = currentTime;
      state.hasGreeted = true;

      // 生成自主对话内容
      console.log(`[AutoChat] 🔄 开始生成对话内容...`);
      const message = await this.generateAutoChatMessage(entity);
      console.log(`[AutoChat] ✅ 生成的消息: "${message}"`);
      
      // 触发回调，通知游戏系统显示对话
      if (this.onAutoChatCallback) {
        console.log(`[AutoChat] 📢 调用回调函数显示对话`);
        this.onAutoChatCallback(entity, message);
      } else {
        console.error(`[AutoChat] ❌ 回调函数未设置！`);
      }

      console.log(`[AutoChat] 🗨️ ${entity.getType()} 自主说话: ${message}`);
    } catch (error) {
      console.error('[AutoChat] ❌ 自主对话生成失败:', error);
      
      // 使用备用回复
      const fallbackMessage = fallbackService.getFallbackResponse(entity.getType());
      console.log(`[AutoChat] 🔄 使用备用回复: "${fallbackMessage}"`);
      if (this.onAutoChatCallback) {
        this.onAutoChatCallback(entity, fallbackMessage);
      }
    }
  }

  /**
   * 生成自主对话内容
   */
  private async generateAutoChatMessage(entity: Entity): Promise<string> {
    const entityType = entity.getType();
    const persona = getEntityPersona(entityType);
    
    if (!persona) {
      throw new Error(`未找到实体 ${entityType} 的个性配置`);
    }

    // 首先尝试使用个性化的自主消息生成
    const gameContext = this.getGameContext(entity);
    const personalityContext = {
      timeOfDay: gameContext.timeOfDay,
      weather: gameContext.weather,
      nearbyBlocks: gameContext.nearbyBlocks,
      nearbyEntities: gameContext.nearbyEntities
    };

    // 使用个性化消息生成器
    const personalityMessage = generateAutonomousMessage(entityType, personalityContext);
    
    // 检查AI服务是否可用，如果可用则进一步个性化
    if (!aiService.isConfigured()) {
      return personalityMessage;
    }

    try {
      // 构建自主对话的上下文
      const context = this.buildAutoChatContext(entity);
      
      // 使用增强的个性化提示词
      const prompt = this.buildEnhancedAutoChatPrompt(persona, context, personalityMessage);
      
      // 调用AI服务生成回复
      const response = await aiService.generateResponse(prompt, context, persona);
      
      // 根据个性调整回复
      const adjustedResponse = adjustResponseByPersonality(entityType, response || personalityMessage, personalityContext);
      
      return adjustedResponse;
    } catch (error) {
      console.warn('AI生成自主对话失败，使用个性化预设消息:', error);
      return personalityMessage;
    }
  }

  /**
   * 构建自主对话上下文
   */
  private buildAutoChatContext(entity: Entity): ConversationContext {
    const gameContext = this.getGameContext(entity);
    
    return {
      entityId: entity.getId(),
      entityType: entity.getType(),
      history: [], // 自主对话不需要历史记录
      gameContext
    };
  }

  /**
   * 构建增强的自主对话提示词
   */
  private buildEnhancedAutoChatPrompt(persona: any, context: ConversationContext, baseMessage: string): string {
    const gameContext = context.gameContext;
    const personalityPrompt = generatePersonalityPrompt(persona.entityType, context);
    
    return `${personalityPrompt}

当前情境：
- 玩家刚刚走近你（距离约${this.detectionRange}格）
- 时间：${gameContext.timeOfDay}
- 天气：${gameContext.weather}
- 周围环境：${gameContext.nearbyBlocks.join('、') || '草地'}

参考消息：${baseMessage}

请基于你的个性特征，生成一句自然的自主对话。要求：
1. 严格按照个性特征和对话风格
2. 考虑当前时间和天气的影响
3. 保持简短（1-2句话）
4. 体现你的情绪状态和行为模式
5. 使用你的特有口头禅和语言习惯

生成对话：`;
  }

  /**
   * 构建自主对话提示词（备用方法）
   */
  private buildAutoChatPrompt(persona: any, context: ConversationContext): string {
    const gameContext = context.gameContext;
    
    return `你是《我的世界》游戏中的一只${persona.name}。玩家刚刚走近你，请主动向玩家打招呼或说一句话。

角色设定：
- 名称：${persona.name}
- 个性：${persona.personality}
- 说话风格：${persona.speechStyle}

当前环境：
- 时间：${gameContext.timeOfDay}
- 天气：${gameContext.weather}

要求：
1. 保持角色个性，说一句简短自然的话
2. 可以是问候、观察环境的话、或者符合角色性格的话
3. 控制在1句话以内
4. 不要问问题，只是简单的表达或问候

请生成一句话：`;
  }

  /**
   * 获取游戏上下文
   */
  private getGameContext(entity: Entity): GameContext {
    if (this.gameContextProvider) {
      return this.gameContextProvider(entity);
    }
    
    // 默认上下文
    return {
      playerPosition: { x: 0, y: 0, z: 0 },
      timeOfDay: 'noon',
      weather: 'clear',
      nearbyBlocks: [],
      nearbyEntities: []
    };
  }

  /**
   * 获取个性化的检测范围
   */
  private getPersonalizedDetectionRange(entity: Entity): number {
    const entityType = entity.getType();
    const persona = getEntityPersona(entityType);
    
    if (!persona) {
      return this.detectionRange;
    }

    // 根据实体个性调整检测范围
    const behaviorPatterns = getBehaviorPatterns(entityType);
    
    // 友好的实体检测范围更大
    if (behaviorPatterns.friendliness > 0.7) {
      return this.detectionRange * 1.5;
    }
    
    // 害羞的实体检测范围更小
    if (behaviorPatterns.shyness > 0.6) {
      return this.detectionRange * 0.7;
    }
    
    // 好奇的实体检测范围稍大
    if (behaviorPatterns.curiosity > 0.6) {
      return this.detectionRange * 1.2;
    }
    
    return this.detectionRange;
  }

  /**
   * 计算两点之间的距离
   */
  private calculateDistance(pos1: Vec3, pos2: Vec3): number {
    const dx = pos1.x - pos2.x;
    const dy = pos1.y - pos2.y;
    const dz = pos1.z - pos2.z;
    return Math.sqrt(dx * dx + dy * dy + dz * dz);
  }

  /**
   * 清理不存在的实体状态
   */
  private cleanupEntityStates(entities: Entity[]): void {
    const existingEntityIds = new Set(entities.map(e => e.getId()));
    
    for (const entityId of this.entityStates.keys()) {
      if (!existingEntityIds.has(entityId)) {
        this.entityStates.delete(entityId);
      }
    }
  }

  /**
   * 设置游戏上下文提供者
   */
  public setGameContextProvider(provider: (entity: Entity) => GameContext): void {
    this.gameContextProvider = provider;
  }

  /**
   * 设置自主对话回调
   */
  public setOnAutoChatCallback(callback: (entity: Entity, message: string) => void): void {
    this.onAutoChatCallback = callback;
  }

  /**
   * 设置检测范围
   */
  public setDetectionRange(range: number): void {
    this.detectionRange = Math.max(1, range);
  }

  /**
   * 设置冷却时间（毫秒）
   */
  public setCooldownDuration(duration: number): void {
    this.cooldownDuration = Math.max(1000, duration); // 最少1秒
  }

  /**
   * 获取实体的自主对话状态
   */
  public getEntityState(entityId: string): AutoChatState | undefined {
    return this.entityStates.get(entityId);
  }

  /**
   * 重置实体的冷却时间
   */
  public resetEntityCooldown(entityId: string): void {
    const state = this.entityStates.get(entityId);
    if (state) {
      state.lastChatTime = 0;
      state.hasGreeted = false;
    }
  }

  /**
   * 获取调试信息
   */
  public getDebugInfo(): any {
    const states = Array.from(this.entityStates.entries()).map(([id, state]) => ({
      entityId: id,
      lastChatTime: new Date(state.lastChatTime).toLocaleTimeString(),
      isInRange: state.isInRange,
      hasGreeted: state.hasGreeted,
      cooldownRemaining: Math.max(0, state.cooldownDuration - (Date.now() - state.lastChatTime))
    }));

    return {
      detectionRange: this.detectionRange,
      cooldownDuration: this.cooldownDuration,
      trackedEntities: this.entityStates.size,
      entityStates: states
    };
  }

  /**
   * 清理所有状态
   */
  public dispose(): void {
    this.entityStates.clear();
    this.gameContextProvider = undefined;
    this.onAutoChatCallback = undefined;
  }
}